package com.kxmall.web.controller.quartz;

import com.kxmall.common.enums.RiderOrderStatusType;
import com.kxmall.common.utils.redis.RedisUtils;
import com.kxmall.order.biz.OrderRiderBizService;
import com.kxmall.rider.mapper.KxRiderOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * 骑手部分订单定时任务
 * Created by admin on 2022/7/21.
 */
@Component
@EnableScheduling
public class CheckRiderQuartz {

    private static final Logger logger = LoggerFactory.getLogger(CheckRiderQuartz.class);

    private static final String RIDER_ORDER_STATUS_LOCK = "RIDER_ORDER_STATUS_QUARTZ_LOCK";

    @Autowired
    private KxRiderOrderMapper riderOrderMapper;
    @Autowired
    private OrderRiderBizService orderRiderBizService;


    /**
     * 订单状态定时轮训
     */
    @Scheduled(cron = "0 * * * * ?")
    public void checkOrderStatus() {
        Lock lock = RedisUtils.lock(RIDER_ORDER_STATUS_LOCK);
        boolean isLocked;
        try {
            isLocked = lock.tryLock(20, TimeUnit.SECONDS);
            if (isLocked) {
                try {
                    Date now = new Date();
                    List<String> nos = riderOrderMapper.selectExpireOrderNos(RiderOrderStatusType.DISPENSE.getCode(), new Date(now.getTime()));
                    if (!CollectionUtils.isEmpty(nos)) {
                        nos.forEach(no -> {
                            try {
                                orderRiderBizService.sendRiderMessageBusiness(no, RiderOrderStatusType.TIMEOUT, 0L, "");
                            } catch (Exception e) {
                                logger.error("[订单状态变更异常] 异常", e);
                            }
                        });
                    }
                } catch (Exception e) {
                    logger.error("[骑手订单状态检测定时任务] 异常", e);
                } finally {
                    lock.unlock();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
